from apps.user.baseViews import *
from apps.user.service import replaceToken
from apps.pay.recordIncomes.dao import RecordIncomesDao

def getAllUsers(self):
    _key = self.request.user.role.key
    _list = UserDao().findAll().select_related('lessee', 'parent', 'rank', 'role')
    if _key == 'admin':
        _list = _list
    else:
        _list = _list.exclude(id=self.request.user.id)
    return _list

# 管理员账号
class AdminViewSet(BaseUserViewSet):
    serializer_class = AdminModelSerializer

    def get_queryset(self):
        params = getRequestParams(self.request)
        _users = getAllUsers(self).exclude(role='custom').exclude(role__isnull=True)
        return _users

    '''创建管理员'''
    @action(methods=['post'], detail=False)
    def createAdmin(self, request):
        params = getRequestParams(request)
        if not params.get('lessee'):
            return Response(response_message('lessee参数必填'))
        if not params.get('role'):
            return Response(response_message('role参数必填'))
        if not params.get('username'):
            return Response(response_message('username参数必填'))
        data = {}
        data['lessee'] = params.get('lessee')
        data['role'] = params.get('role')
        data['username'] = params.get('username')
        data['password'] = params.get('password')
        data['phone'] = params.get('phone')
        data['nickname'] = params.get('nickname')
        data['realname'] = params.get('realname')
        if isEmptyStr(params.get('password')):
            data['password'] = random_uuid()
        UserDao().create(data)

        return Response(response_success('创建成功'))

# tree
class UserTreeViewSet(BaseUserViewSet):
    serializer_class = UserTreeModelSerializer

    def get_queryset(self):
        params = getRequestParams(self.request)
        _lists = getAllUsers(self).filter(role='custom')
        parentId = params.get('parentId')
        if parentId:
            _lists = _lists.filter(parent = parentId)
        else:
            _lists = _lists.filter(parent__isnull=True)
        return _lists.order_by('id')

class UserViewSet(BaseUserViewSet):

    def get_queryset(self):
        _list = getAllUsers(self).filter(role='custom')
        return _list

    '''账号密码登录'''
    @action(methods=['post'], detail=False, authentication_classes=[], permission_classes=[])
    def login(self, request):
        params = getRequestParams(self.request)
        _users = UserDao().findAll().filter(username=params.get('username'), password=params.get('password')).exclude(
            role='custom')
        # 更新token
        if not _users.exists():
            return Response(response_message('账号或密码错误！'))
        _userId = _users.first().id
        token = replaceToken(_userId)
        return Response(response_success({'token': token.key}))

    '''获取用户信息'''

    @action(methods=['post'], detail=False)
    def getUserInfo(self, request):
        params = getRequestParams(self.request)
        obj = UserDao().findOneByObjId(self.request.user.id)
        model = UserModelDetailSerializer(obj).data
        return Response(response_success(model))

    @action(methods=['post'], detail=False)
    def getUserInfoById(self, request):
        params = getRequestParams(self.request)
        if not params.get('obj_id'):
            return Response(response_message(('obj_id参数必填')))
        obj = UserDao().findOneByObjId(params.get('obj_id'))
        model = UserModelDetailSerializer(obj).data
        return Response(response_success(model))

    '''更新用户信息'''

    @action(methods=['post'], detail=False)
    def updateUser(self, request):
        params = getRequestParams(self.request)
        UserDao().update(request.user.id, params)
        return Response(response_success('修改成功'))

    '''退出登录'''

    @action(methods=['post'], detail=False, authentication_classes=[], permission_classes=[])
    def logout(self, request):
        params = getRequestParams(request)
        _tokens = Token.objects.filter(key=params.get("token"))
        if _tokens.count() > 0 and _tokens.first().user.username != 'openshop':
            _tokens.delete()
        return Response(response_success("操作成功"))

    '''管理员修改密码'''

    @action(methods=['post'], detail=False)
    def updatePwdForAdmin(self, request):
        params = getRequestParams(request)
        if not params.get('oldPassword'):
            return Response(response_message("旧密码不能为空"))
        if not params.get('password'):
            return Response(response_message("新密码不能为空"))
        _user = UserModel.objects.get(id=params.get('userId'))
        if _user.password != params.get('oldPassword'):
            return Response(response_message("旧密码验证失败！"))
        _user.password = params.get('password')
        _user.save()
        return Response(response_success('密码修改成功'))

    '''管理员重置密码'''

    @action(methods=['post'], detail=False)
    def resetPwdForAdmin(self, request):
        params = getRequestParams(request)
        if not params.get('password'):
            return Response(response_message("新密码不能为空"))
        _user = UserModel.objects.get(id=params.get('userId'))
        _user.password = params.get('password')
        _user.save()
        # 密码重置之后，删除token
        old_token = Token.objects.filter(user_id=_user.id)
        old_token.delete()
        return Response(response_success('密码修改成功'))

    '''充值收益'''
    @action(methods=['post'], detail=False)
    def updateUserForAddIncome(self, request):
        params = getRequestParams(request)
        if not params.get('money'):
            return Response(response_message('请填写金额'))
        if not params.get('userId'):
            return Response(response_message('userId参数必填'))
        _user = UserDao().findOneByObjId(params.get('userId'))
        UserDao().addWallet('incomes', _user, params.get('money'))
        data = {}
        data['lessee'] = _user.lessee.id
        data['scene'] = 'addIncomeFromAdmin'
        data['user'] = _user.id
        data['fromUser'] = self.request.user.id
        data['orderId'] = ''
        data['money'] = params.get('money')
        data['payway'] = 'incomes'
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        data['remark'] = params.get('remark')
        RecordIncomesDao().create(data)
        return Response(response_success('充值成功'))

    '''扣除收益'''
    @action(methods=['post'], detail=False)
    def updateUserForSubIncome(self, request):
        params = getRequestParams(request)
        if not params.get('money'):
            return Response(response_message('请填写金额'))
        if not params.get('userId'):
            return Response(response_message('userId参数必填'))
        _user = UserDao().findOneByObjId(params.get('userId'))
        UserDao().subWallet('incomes', _user, params.get('money'))
        data = {}
        data['lessee'] = _user.lessee.id
        data['scene'] = 'subIncomeFromAdmin'
        data['user'] = _user.id
        data['fromUser'] = self.request.user.id
        data['orderId'] = ''
        data['money'] = params.get('money')
        data['payway'] = 'incomes'
        data['changeWay'] = 'sub'
        data['orderStatus'] = 'FINISH'
        data['remark'] = params.get('remark')
        RecordIncomesDao().create(data)
        return Response(response_success('扣除成功'))
